#######################################################
# Example of FSTDEVS Processor
# Author: moonho.hwang@gmail.com
#   Date: Oct.19.2011
#######################################################
from XSY.DEVS.FRTDEVS import *
from XSY.DEVS.CoupledDEVS import *
from XSY.DEVS.SimEngine import SimEngine
from XSY.DEVS.VeriEngine import VeriEngine

class Processor(FSTDEVS):
   '''a processor model based on FSTDEVS'''
   def __init__(m, n, meant, parent=None):
      '''constructor'''
      FSTDEVS.__init__(m, n, parent) 
      m.work = None
      m.meant = meant
      m.addInputPorts('?in')
      m.addOutputPorts('!out', '!out_signal')

   def delta_0(m):
      '''initial state'''
      m.phase = 'IS' # initial send 
      m.work = None

   def rv_tau(m):
      '''lifespan range function'''
      if m.phase == 'IS':
         return float(0)
      elif m.phase == 'S':
         return RV_Exponential(m.meant) # 
      else:
         return float('inf') # 

   def delta_x(m, x):
      '''external transition function'''
      if x.port == m.IP['?in'] and m.phase == 'W':
         m.phase = 'S'
         m.work = x.value
         return True
      else:
         return False
               
   def delta_y(m):
      '''output and internal transition function'''
      if m.phase == 'S':
         y = PortValue(m.OP["!out"], m.work)
         m.phase = 'W'
         m.work = None
         #raw_input("@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n")
         return y
      elif m.phase == 'IS':
         m.phase = 'W'
         y = PortValue(m.OP["!out_signal"])
         return y

   def get_state(m):
      '''get the state'''
      return m.phase, m.work

   def set_state(m, s):
      '''set the state as s'''
      m.phase, m.work = s
 
def runSimulation(md):
   engine = SimEngine(md)

   #---- setting StepByStep and DES simulation only ----
   engine.StepByStep = True
   engine.sfactor = float('inf')
   #----------------------------------------------------
   engine.runInteractiveMenu()

if __name__ == '__main__':
   md = Processor('Proc', 10)
   runSimulation(md) 
   print "good bye~!" 
